package pl.edu.pw.polygen.modeler.client.properties;

import pl.edu.pw.polygen.modeler.client.graph.IPropertyChangeListener;
import pl.edu.pw.polygen.modeler.client.object.IPolygenObject;
import pl.edu.pw.polygen.modeler.client.object.Segment;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;

public class SegmentProperties extends Composite implements Paintable{
	private VerticalPanel panel;
	
	private TextBox boundary;
	private VertexProperties beginVertexProperies;
	private VertexProperties endVertexProperties;
	private IPolygenObject polygenObject;
	
	public SegmentProperties(){
		super();
		this.initialize();
	}
	
	private void initialize(){
		panel = new VerticalPanel();
		beginVertexProperies = new VertexProperties();
		endVertexProperties = new VertexProperties();
		
		HorizontalPanel boundaryPanel = getBoundaryPanel();
		panel.add(boundaryPanel);
		beginVertexProperies.setTitle("Vertex A");
		panel.add(beginVertexProperies);
		endVertexProperties.setTitle("Vertex B");
		panel.add(endVertexProperties);
		initWidget(panel);
	}
	
	private HorizontalPanel getBoundaryPanel(){
		HorizontalPanel boundaryPanel = new HorizontalPanel();
		boundaryPanel.setBorderWidth(1);
		boundary = new TextBox();
		boundary.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				try{
					polygenObject.getModel().setBoundary(Integer.parseInt(boundary.getText()));
					((IPropertyChangeListener)polygenObject).notifyChanges();
				}catch(NumberFormatException e){
					
				}
			}
		});
		
		boundary.setTitle("boundary");
		Label boundaryLabel = new Label("boundary");
		boundaryLabel.setWidth("51px");
		boundaryPanel.add(boundaryLabel);
		boundaryPanel.add(boundary);
		return boundaryPanel;
	}
	
	public void setSegment(Segment segment){
		polygenObject = segment;
		boundary.setText(segment.getModel().getBoundary()+"");
		beginVertexProperies.setVertex(segment.getBeginVertex());
		endVertexProperties.setVertex(segment.getEndVertex());
	}
	
	
	@Override
	public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
		beginVertexProperies.updateFromUIDL(uidl, client);
		endVertexProperties.updateFromUIDL(uidl, client);
	}
}
